package tt.dz.egobus.servicemanager.facade.interator;

import tt.dz.egobus.i18n.SingletonI18NProperties;
import tt.dz.egobus.servicemanager.bean.ServiceManagerCodeStatus;
import tt.dz.egobus.servicemanager.core.exception.BusinessException;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Anson
 * @date 17-3-21
 * @name 添加了日志输出拦截
 * @since 1.0.2
 */
public enum FacadeFactoryLoggerInterceptorHolder implements FacadeFactory {
    LOGGER_FACADE;

    private AtomicBoolean isInit = new AtomicBoolean(false);

    private FacadeConfigFactory facadeFactory;

    FacadeFactoryLoggerInterceptorHolder() {

    }

    /**
     * 初始化facade相关配置
     */
    public FacadeFactoryLoggerInterceptorHolder init() {
        if (!this.isInit.get()) {
            if (facadeFactory == null) {
                CglibProxyFacdeFactory facadeFactory = new CglibProxyFacdeFactory();
                InterceptorChain chain = new InterceptorChain();
                chain.addChain(new LoggerInterceptor());
                facadeFactory.setInterceptor(chain);
                facadeFactory.setContext(new ClassPathScanFacadeContext());
                facadeFactory.doScan();
                this.facadeFactory = facadeFactory;
                this.isInit.set(facadeFactory.isDoScan());
            }
        }
        return this;
    }

    @Override
    public <E> E getBean(String facadeName, Class<E> clazz) {
        init();
        if (facadeFactory == null) {
            throw new BusinessException(
                    SingletonI18NProperties.SINGL_TON.
                            properties().get(String.valueOf(ServiceManagerCodeStatus.SYSTEM_CODE_ERROR)));
        }
        return facadeFactory.getBean(facadeName, clazz);
    }
}
